#include "fb.hpp"


Framebuffer::Framebuffer(int height,int width)
{
        h = height;
        w = width;
        // cria a textura representando o framebuffer
        glGenTextures( 1, &id );
        
        // aloca a memoria para o framebuffer
        line_size = w * 3;
        size = h * line_size;
        
        fb_data = new char[size];
}


Framebuffer::~Framebuffer(void)
{
        delete fb_data;
}

// supoe x, y no espaco normalizado (-1 .. +1)

void Framebuffer::setPixel(const double x,const double y,const Cor& _cor)
{       
        const double r = _cor.getR();
        const double g = _cor.getG();
        const double b = _cor.getB();
        int px = (int) ( ( (x + 1.0) / 2.0 ) * w );
        int py = (int) ( ( (y + 1.0) / 2.0 ) * h );
        
        if (px < 0) px = 0;
        else if (px > w-1) px = w-1;
        
        if (py < 0) py = 0;
        else if (py > h-1) py = h-1;
        
        const int offset = py*line_size + px*3;
        
        int ir = r * 255.0;
        int ig = g * 255.0;
        int ib = b * 255.0;
        char cr,cg,cb;
        
        cr = max(0,min(ir,255));
        cg = max(0,min(ig,255));                
        cb = max(0,min(ib,255));
        
        
        fb_data[ offset + 0 ] = cr;
        fb_data[ offset + 1 ] = cg;
        fb_data[ offset + 2 ] = cb;
        
}
void Framebuffer::show(void) const
{
        // ativa textura
        glBindTexture( GL_TEXTURE_2D, id );
        
        // Registra  a textura
        glTexImage2D( GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, fb_data );
        
        // ativa texturizacao
        glEnable( GL_TEXTURE_2D );
        
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
        
        // deixa nossa matriz num estado normalizado
        glMatrixMode( GL_PROJECTION );
        glLoadIdentity();
        
        glMatrixMode( GL_MODELVIEW );
        glLoadIdentity();
                
                glBegin( GL_QUADS );
                        glTexCoord2f( 0, 0 );
                        glVertex2f( -1, -1 );
                        
                        glTexCoord2f( 1, 0 );
                        glVertex2f( +1, -1 );
                        
                        glTexCoord2f( 1, 1 );
                        glVertex2f( +1, +1 );
                        
                        glTexCoord2f( 0, 1 );
                        glVertex2f( -1, +1 );
                glEnd();
        glDisable( GL_TEXTURE_2D );
}

